import request from "./request.js";
import {
	baseURL
} from "./data.js";
import {
	applyId,
	loginFrom
} from "./data.js";

export const login = async (provider) => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: provider,
			onlyAuthorize: true,
			// scopes: 'auth_user',
			async success(loginRes) {
				console.log("获取登录凭证：", provider, loginRes);
				uni.setStorageSync("loginProvider", provider);
				if (loginRes.errMsg === "login:ok") {
					const shareUserId = uni.getStorageSync("shareUserId") || "";
					let res = await request("/api/user/user/login", {
						code: loginRes.code,
						loginFrom: loginFrom[provider],
						userId: shareUserId,
						anonymousCode: loginRes.anonymousCode,
					});
					console.log("登录接口", res.data);
					if (res.status === 200) {
						uni.removeStorageSync("shareUserId"); //登录成功删除分享者id
						uni.setStorageSync("Authorization_token", res.data.token || "");
						uni.setStorageSync("currentUserId", res.data.userId || "");
						uni.setStorageSync("aliUserId", res.data.aliUserId || "");
						getUserInfo(res.data.token);
						// uni.$u.toast('登录成功');
						uni.showToast({
							title: "登录成功",
							icon: "success",
						});

						resolve(res);
					} else {
						uni.showToast({
							title: "登录失败",
							icon: "error",
						});
						reject(res.message);
					}
				}
			},
			fail(err) {
				console.log(err, "loginErr");
			},
		});
	});
};

export const checkLogin = () => {
	return new Promise((resolve, reject) => {
		uni.getProvider({
			service: "oauth",
			success: async function(res) {
				if (res.provider.includes("weixin") && wx.getPrivacySetting) {
					wx.getPrivacySetting({
						success: async (res2) => {
							console.log("协议显示的值", res2);
							// PrivacyProtocol.needAuthorization = res.needAuthorization
							if (res2.needAuthorization) {
								// 需要弹出隐私协议
								// PrivacyProtocol.privacyContractName = res.privacyContractName;
								reject("noCheck");
							} else {
								await login(res.provider[0]);
								resolve();
							}
							// uni.setStorageSync("PrivacyProtocol", PrivacyProtocol);
						},
					});
				} else {
					await login(res.provider[0]);
					resolve();
				}
			},
		});
	});
};

async function getPayRes(orderId) {
	console.log('payRes', orderId)
	let payRes = await uni.$request(
		'/api/busi/douyin/query', {
			orderId
		});
	console.log('payRes', payRes)
	let payStatus = payRes.data;
	// 如果还在支付过程中，隔一秒过后再查询
	if (payStatus === 'PROCESS') {
		payStatus = await new Promise((resolve) => {
			setTimeout(() => {
				resolve(waitPayRes(
					orderId
				));
			}, 1000)
		});
	}
	return payStatus;
}

// 统一支付
export const uniPay = (payInfo) => {
	console.log("支付需要的信息", payInfo);
	return new Promise((resolve, reject) => {
		const {
			nonceStr,
			prepayId,
			timeStamp,
			paySign,
			orderNo,
			tradeNo,
			orderId,
			orderToken,
			byteAuthorization, //抖音通用支付
			data, //抖音通用支付
		} = payInfo;

		uni.getProvider({
			service: "payment",
			success: function(res) {
				let provider = res.provider[0];
				console.log(res.provider);
				let orderInfo = {};
				if (provider === "wxpay") {
					// 微信支付
					orderInfo = {
						timeStamp: String(timeStamp),
						nonceStr: nonceStr,
						package: `prepay_id=${prepayId}`,
						signType: "RSA",
						paySign: paySign,
					};
				} else if (provider === "alipay") {
					orderInfo = {
						orderInfo: String(tradeNo),
					};
				} else if (provider === "toutiao") { //抖音走自己的通用支付
					// orderInfo = {
					//   orderInfo: {
					//     order_id: orderId,
					//     order_token: orderToken,
					//   },
					//   service: 5,
					// };
					if (tt.canIUse('requestOrder') && tt.canIUse('getOrderPayment')) {
						tt.requestOrder({
							data,
							byteAuthorization,
							success({
								orderId
							}) {
								console.log('预下单成功', orderId)
								
								tt.getOrderPayment({ 
									orderId,
									async success(res) {
										console.log('getOrderPayment success', res);
										const payStatus = await getPayRes(orderNo);
										console.log('payStatus', payStatus)
										if (payStatus === 'SUCCESS') {
											resolve({
												orderNo,
											})
										} else {
											uni.$u.toast('支付失败')
										}
									},
									fail(res){
										console.log('getOrderPayment fail', res);
									}
								});
							},
							fail(res) {
								console.log('fail', res);
							}
						});

					} else {
						uni.$u.toast('暂不支持，请升级到最新版本抖音');
					}
					return;

				} else if (provider === "kuaishoupay") {
					orderInfo = {
						serviceId: "1", //ks.pay文档，固定值
						orderInfo: {
							order_no: orderId,
							order_info_token: orderToken,
						},
					};
				}
				uni.requestPayment({
					provider,
					success: function(res) {
						console.log("支付成功--", res);
						if (provider == "alipay") {
							if (res.resultCode == 9000) {
								resolve({
									orderNo,
								});
							} else {
								reject();
							}
						} else if (provider == "toutiao") {
							if (res.code == 0) {
								resolve({
									orderNo,
								});
							} else {
								reject();
							}
						} else if (provider == "wxpay") {
							resolve({
								orderNo,
							});
						} else if (provider == "kuaishoupay") {
							console.log("快手支付成功");
							resolve({
								orderNo,
							});
						}
						// console.log('success:' + JSON.stringify(res));
					},
					fail: function(err) {
						console.log('支付失败:' + JSON.stringify(err));
						reject();
					},
					...orderInfo,
				});
			},
		});
	});
};

export const getPaymentType = () => {
	return new Promise((resolve) => {
		uni.getProvider({
			service: "payment",
			success: async (res) => {
				resolve(res.provider[0]);
			},
		});
	});
};

export const getUserInfo = () => {
	return uni.$request("/api/user/user/details").then((res) => {
		if (res.status == 200) {
			uni.setStorageSync("userInfo", res.data);
			uni.setStorageSync("userLogin", true);
		}
	});
};

export const queryPackageApi = (types) => {
	let promises = [];
	for (let type of types) {
		promises.push(
			uni.$request("/api/busi/package/select", {
				type,
			})
		);
	}
	return Promise.all(promises);
};

export const uploadFile = (localUrl) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseURL + "/api/busi/photo/uploadOss",
			filePath: localUrl,
			name: "file",
			header: {
				Authorization: "Bearer " + uni.getStorageSync("Authorization_token"),
			},
			formData: {
				aliUserId: uni.getStorageSync("aliUserId"),
			},
			async success(res) {
				console.log("uploadFile", res);
				const data = JSON.parse(res.data);
				if (data.status === 200) {
					const fileResUrl = data.data;
					resolve(fileResUrl);
				} else if (data.status === 401) {
					//登录超时，自动重新登录
					await uni.$login();
					// 再次上传，获取地址返回
					let fileUrl = await uploadFile(localUrl);
					console.log("fileUrl", fileUrl);
					resolve(fileUrl);
				} else {
					uni.hideLoading({
						success() {
							uni.$u.toast(data.message || "图片信息异常，请重新上传");
						},
					});
				}
			},
			fail() {
				uni.hideLoading({
					success() {
						uni.$u.toast("图片信息异常，请重新上传");
					},
				});
				reject();
			},
		});
	});
};

export const checkUploadImage = (data) => {
	data = data || {};
	const params = data.params || {};
	const limit = data.limit || {};
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: params.count || 1, //默认9
			sizeType: params.sizeType || ["compressed"], //可以指定是原图还是压缩图，默认二者都有
			sourceType: params.sourceType || ["album"], //从相册选择
			success: async function(res) {
				const tempImage = res.tempFilePaths[0];
				let {
					width,
					height,
					type
				} = await getImageInfo(tempImage);
				let fileSize = await getFileSize(tempImage, false);
				const limitWidth = limit.width || 2000;
				const limitHeight = limit.height || 2000;
				if (width > limitWidth) {
					uni.$u.toast(`图片宽度过大，不能超过${limitWidth}px`);
					return;
				}
				if (height > limitHeight) {
					uni.$u.toast(`图片高度过大，不能超过${limitHeight}px`);
					return;
				}
				// 校验大小
				if (limit.fileSize) {
					console.log("校验大小", fileSize, limit.fileSize);
					if (fileSize > limit.fileSize) {
						uni.$u.toast(`文件过大，不能超过${limit.fileSize}px`);
						return;
					}
				}
				// 校验格式
				if (limit.types) {
					console.log("校验格式", type.toUpperCase());
					if (!limit.types.includes(type.toUpperCase())) {
						uni.$u.toast(`仅支持${types.join("、")}图片格式`);
						return;
					}
				}

				uni.showLoading({
					title: "检测中",
				});
				let uploadedSrc = await uploadFile(tempImage);
				uni.hideLoading();
				resolve({
					uploadedSrc,
					width,
					height,
					type,
					fileSize,
				});
			},
		});
	});
};
// px / ppi = 英寸
// 1英寸 = 25.4mm
// px = mm / 25.4 *ppi
// mm = px / ppi * 25.4
export const pxTomm = (pxVal, ppi = 300) => {
	return Math.round((pxVal / ppi) * 25.4);
};
export const mmTopx = (mmVal, ppi = 300) => {
	return Math.round((mmVal / 25.4) * ppi);
};

/*RGB转换为16进制*/
export const colorRgbToHex = (rgbStr) => {
	//十六进制颜色值的正则表达式
	const reg =
		/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8}|[0-9a-fA-f]{6}[0-9]{2})$/;
	if (reg.test(rgbStr)) {
		return rgbStr;
	} else {
		const rgbArray = rgbStr
			.replace(/(?:\(|\)|rgba|rgb|RGBA|RGB)*/g, "")
			.split(",");
		let strHex = "#";
		for (let i = 0; i < rgbArray.length; i++) {
			if (i !== 3) {
				if (rgbArray[i] == "0") {
					strHex += "00";
				} else {
					let newItem = Number(rgbArray[i]).toString(16);
					if (newItem.length < 2) {
						newItem = "0" + newItem;
					}
					strHex += newItem;
				}
			} else {
				strHex +=
					rgbArray[i] == "0" ? "" : Math.floor(rgbArray[i] * 255).toString(16);
			}
		}
		return strHex;
	}
};
export const downloadImg = (imageUrl) => {
	uni.downloadFile({
		url: imageUrl,
		header: {
			Authorization: "Bearer " + uni.getStorageSync("Authorization_token"),
		},
		success(res) {
			uni.saveImageToPhotosAlbum({
				filePath: res.tempFilePath,
				success() {
					uni.showToast({
						title: "保存成功",
						icon: "success",
					});
				},
			});
		},
		fail(err) {
			console.log(err);
			uni.showToast({
				title: err,
				icon: "error",
			});
		},
	});
};

// 检测权限
const isAuthorize = (scopeValue) => {
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success(res) {
				console.log(res.authSetting);
				resolve(res.authSetting[scopeValue]);
			},
			fail(res) {
				reject(false);
			},
		});
	});
};

// 打开权限设置界面并等待返回，获取对应scope权限
const settingAuthorize = (scopeValue) => {
	return new Promise((resolve, reject) => {
		uni.openSetting({
			success(res) {
				console.log("settingAuthorize", res.authSetting);
				resolve(res.authSetting[scopeValue]);
			},
			fail(res) {
				reject(false);
			},
		});
	});
};

const authorize = (scopeValue) => {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: scopeValue,
			success: () => {
				resolve(true);
			},
			fail(res) {
				reject(false);
			},
		});
	});
};

const showModal = ({
	title,
	content
}) => {
	return new Promise((resolve, reject) => {
		uni.showModal({
			success(res) {
				if (res.confirm) {
					console.log("用户点击确定");
					resolve(true);
				} else if (res.cancel) {
					console.log("用户点击取消");
					resolve(false);
				}
			},
		});
	});
};

const checkAuth = async (scope) => {
	const loginProvider = uni.getStorageSync("loginProvider");
	// 仅微信支持校验是否授权
	if (loginProvider !== "weixin") return true;
	// 授权弹窗
	const isAuthor = await authorize(scope);
	if (!isAuthor) {
		let isConfirm = await showModal({
			title: "温馨提示",
			content: "您未授权访问相册权限，点击确认去设置",
		});
		if (!isConfirm) return false; //取消
		// 点击确认，去设置，并在返回时获取结果
		let authRes = await settingAuthorize(scope);
		return authRes;
	}
	return true;
};

const getLocalFile = (imageUrl) => {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: imageUrl,
			header: {
				Authorization: "Bearer " + uni.getStorageSync("Authorization_token"),
			},
			success(res) {
				resolve(res.tempFilePath);
			},
			fail(err) {
				console.error(err);
				reject();
			},
		});
	});
};
let scopeAlbum = "scope.writePhotosAlbum";
// #ifdef MP-TOUTIAO
scopeAlbum = "scope.album";
// #endif

export const savePhoto = (imageUrl) => {
	return new Promise(async (resolve, reject) => {
		let isAuthPhoto = await checkAuth(scopeAlbum);
		if (!isAuthPhoto) return;
		let localFile = await getLocalFile(imageUrl);
		uni.saveImageToPhotosAlbum({
			filePath: localFile,
			success() {
				resolve();
			},
			fail(res) {
				console.log("saveImageToPhotosAlbum 调用失败", res);
				// 支付宝增加提示
				// #ifdef MP-ALIPAY
				const platform = my.env.platform;
				if (err.error === 15) {
					// 提示用户开启相册权限
					if (platform === "iOS") {
						my.showAuthGuide({
							authType: "PHOTO",
							complete(res) {
								if (res.shown) {
									console.log("已展示权限引导");
								} else {
									uni.$u.toast(
										"保存失败，请在系统设置中为支付宝并开启相册权限"
									);
								}
							},
						});
					} else if (platform === "Android") {
						uni.$u.toast(
							"保存失败，请在系统设置找到支付宝应用并开启文件和多媒体写入权限"
						);
					}
				}
				// #endif

				reject();
			},
		});
	});
};

export const saveAllPhoto = async (data) => {
	console.log("scopeAlbum", scopeAlbum);
	let isAuthPhoto = await checkAuth(scopeAlbum);
	console.log("isAuthPhoto", isAuthPhoto);
	if (!isAuthPhoto) return;
	const photoUrlList = Object.values(data.photoUrls || {});
	const typesetUrlList = Object.values(data.typesetUrls || {});
	console.log("saveAllPhoto", [...photoUrlList, ...typesetUrlList]);
	try {
		let res = await [...photoUrlList, ...typesetUrlList].map((item) =>
			savePhoto(item)
		);
		console.log("res", res);
		uni.showToast({
			title: "已保存到相册",
			icon: "success",
		});
	} catch (e) {
		//TODO handle the exception
		uni.showToast({
			title: "保存失败，请联系客服",
			icon: "error",
		});
	}
};

// 获取文件大小，单位KB
export const getFileSize = (src, isOnline = true) => {
	return new Promise(async (resolve, reject) => {
		const file = uni.getFileSystemManager();
		if (isOnline) {
			src = await getLocalFile(src);
		}
		// 自定义图片，获取文件大小
		file.getFileInfo({
			filePath: src,
			success(res) {
				resolve(Math.ceil(res.size / 1024));
			},
			fail(res) {
				console.log("fail", res);
				reject();
			},
		});
	});
};

export const getImageInfo = (imgSrc) => {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src: imgSrc,
			success(res) {
				resolve(res);
			},
			fail() {
				reject();
			},
		});
	});
};

export const getImgScaleStyle = (width, height, limit = 250) => {
	let large = width > height ? width : height; //取较长的一边
	let scale = large < limit ? 1 : limit / large; //较长边大于limit px则缩放，另一边也按该比例缩放
	return {
		width: width * 2 * scale + "rpx",
		height: height * 2 * scale + "rpx",
	};
};

export const getQueryStr = (data) => {
	let str = "";
	for (let key in data) {
		str += `&${key}=${data[key]}`;
	}
	return str.slice(1);
};
export const resolveImage = (path) => {
	if (path.startsWith("/static")) {
		return path;
	} else {
		if (path[0] !== "/") path = "/" + path;
		return uni.$imagePrefix + path;
	}
};

export const getProviderIconSrc = () => {
	const iconMap = {
		weixin: 'wechat-address.png',
		alipay: 'alipay.png',
		toutiao: 'favicon.png',
	};
	let loginProvider = uni.getStorageSync('loginProvider');
	return iconMap[loginProvider]
}